package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public void save(Role role, Long[] ids) {
        roleMapper.insert(role);
        saveRelation(role, ids);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);
        // 先删除原本中间表关联的数据,再重新添加
        roleMapper.deleteRelation(role.getId());
        saveRelation(role, ids);
    }

    private void saveRelation(Role role, Long[] ids) {
        if (ids != null && ids.length >0) {
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo<>(roleMapper.selectForList(qo));

    }
}
